package com.company.project.utils;


import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;

/**
 * AES 加密
 */
public class AesUtils {

    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    /**
     * 加密
     *
     * @param content    加密的字符串A
     * @param encryptKey key值
     * @return
     * @throws Exception
     */
    public static String AESEncrypt(String content, String encryptKey) throws Exception {
//        System.out.println("加密字符串:"+content);
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
        byte[] b = cipher.doFinal(content.getBytes("utf-8"));
        // 采用base64算法进行转码,避免出现中文乱码
        return Base64.encodeBase64String(b);
    }

    /**
     * 解密
     *
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     * @return
     * @throws Exception
     */
    public static String AESDecrypt(String encryptStr, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        // 采用base64算法进行转码,避免出现中文乱码
        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }


    /**
     * AES解密
     *
     * @param data           //密文，被加密的数据
     * @param key            //秘钥
     * @param iv             //偏移量
     * @param encodingFormat //解密后的结果需要进行的编码
     * @return
     * @throws Exception
     */
    public static String decryptWx(String data, String key, String iv, String encodingFormat) {


        /**
         * 这个地方调用BouncyCastleProvider
         *让java支持PKCS7Padding
         */
        Security.addProvider(new BouncyCastleProvider());
//        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        //被加密的数据
        byte[] dataByte = Base64.decodeBase64(data);
        //加密秘钥
        byte[] keyByte = Base64.decodeBase64(key);
        //偏移量
        byte[] ivByte = Base64.decodeBase64(iv);
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, encodingFormat);
                return result;
            }
            return null;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidParameterSpecException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
//        String appId = "202008130946001591768935";
//        String key = "ebVhf4dBODYfRbZy";

        System.out.println("01".contains("01"));
        String appId = "11000000049";
        String key = "rW@vM2UlXKGe2V%!";

//        String content = "{\"prescId\":\"200909010203\",\"patientId\":\"4140962\"}";
//        String content = "{\"patientId\":\"4140962\",\"prescId\":\"200909010203\",\"drugStoreNo\":\"4140962\",\"amount\":\"10.22\",\"selfAmount\":\"10.22\",\"drugList\":[{\"drugCode\":\"\",\"packageUnit\":\"次\",\"drugName\":\"各类病原体RNA测定(新冠筛查)(实时荧光PCR)\",\"prescId\":\"200909010203\",\"drugId\":\"\",\"id\":12470,\"drugSort\":\"1\",\"packageQuantity\":\"1\",\"drugSpec\":\"/\",\"price\":\"0.1\",\"totalPrice\":\"0.1\"},{\"drugCode\":\"\",\"packageUnit\":\"人份\",\"drugName\":\"新冠病毒核酸检测试剂盒(荧光PCR法)(DA)\",\"prescId\":\"200909010203\",\"drugId\":\"\",\"id\":12471,\"drugSort\":\"2\",\"packageQuantity\":\"1\",\"drugSpec\":\"48人份/盒\",\"price\":\"0.2\",\"totalPrice\":\"0.2\"}]}";
//        String content = "{\"isExpress\":\"1\",\"expressNo\":\"SF-0001111\",\"expressCompany\":\"SF\",\"expressPhone\":\"15396223961\",\"expressAddress\":\"厦门-海天路-外口公寓\",\"expressReceiver\":\"彭辰锡\",\"prescId\":\"200909010203\",\"patientId\":\"4140962\"}";
//        String content = "{\"prescStatus\":\"2\",\"prescId\":\"200909010203\",\"patientId\":\"4140962\"}";
//        String content = "{\"patientId\":\"20200718164026\"}";
        String content = "<REQ><HOS_ID><![CDATA[1001]]></HOS_ID></REQ>";
        System.out.println("*************** 加密结果 **************");

//        System.out.println(AESEncrypt(content,"2098D32C4D1399EC"));
//        System.out.println("*************** 解密  结果 **************");
//        System.out.println(System.currentTimeMillis() / 1000);
//        String resjsondata = "Gc4zC0Wdp9lVJBaRlPNh+2cPVfBXkrjEg7iJ8OS8UElWVf/UdJOkl6fsnV3wVS";
//        System.out.println(AESDecrypt(resjsondata, "2098D32C4D1399EC"));//解密

//        String md5txt=  "FUN_CODE=<![CDATA[1005]]>&REQ_ENCRYPTED=<![CDATA[rf7ELgT7MR5fWkvpDizQul6eZPNhjIRvCbBF7X+W0E/TwI/b72SZpfMGPdZB+RYjWR6zjBvGRyJmuN2a8dqikg==]]>&USER_ID=<![CDATA[000000]]>&KEY=2098D32C4D1399EC";
//        System.out.println(DigestUtils.md5Hex(md5txt).toUpperCase());
    }
}
